package com.xbongbong.crm.perform.query.detail;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDetailTopInfoService;
import com.xbongbong.crm.service.permission.RefundPermissionServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.OwnerAndCoUserHelp;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.CustomerUserPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.LinkListService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.explain.FormDataDetailFormExplainHandleName;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.pro.appdetail.pojo.MobileDetailDirectBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailManagerBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.RefundStatusEnum;
import com.xbongbong.pro.enums.permission.enums.UpdateProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.paas.service.BusinessButtonService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.RefundUserEntity;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.RefundUserModel;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.NameUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;

/**
 * @author 吴峰
 * @date 2022/06/14 17:26
 */
@Slf4j
@Service("refundDetailTopInfoServiceImpl")
public class RefundDetailTopInfoServiceImpl extends AbstractCrmDetailTopInfoService {

    @Resource
    private RefundPermissionServiceImpl refundPermissionService;
    @Resource
    private OwnerAndCoUserHelp ownerAndCoUserHelp;
    @Resource
    private FormDataDetailFormExplainHandleName formDataDetailFormExplainHandleName;
    @Resource
    private RefundModel refundModel;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private RefundUserModel refundUserModel;
    @Resource
    private UserModel userModel;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private BusinessButtonService businessButtonService;
    @Resource
    private LinkListService linkListService;
    @Resource
    private DetailTabConfigService detailTabConfigService;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.REFUND.getCode());
    }

    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        if (loginUser.isMaxDataPermission()){
            return;
        }
        //校验用户是否有查看权限
        verifyQueryPermission(formEntity.getBusinessType(), loginUser, formEntity.getSaasMark(), formEntity.getMenuId(), paasFormDataEntityExt.getFlowStatus());
        //团队权限&共享权限校验
        refundPermissionService.checkPermission(formEntity, paasFormDataEntityExt, loginUser, subBusinessType);
    }


    @Override
    public JSONObject analysisData(PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        Long formId = paasFormDataEntityExt.getFormId();
        List<FieldAttrEntity> list = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(list.size());
        list.forEach(item->explainMap.put(item.getAttr(), item));

        ParseSingleRowDataVO parseSingleRowDataVO = commonAnalysisData(paasFormDataEntityExt, handlerExplainDTO, handlerExplainVO, list, explainMap);
        JSONObject data = parseSingleRowDataVO.getResult();
        SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
        BeanUtil.copyProperties(handlerExplainDTO, saasAnalysisDataDTO);
        saasAnalysisDataDTO.setFormId(formId);
        refundModel.formatData(saasAnalysisDataDTO, data);
        //处理千分位
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        formDataGetVO.setData(data);
        formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, list, false);
        return data;
    }

    @Override
    public List<MobileDetailMoneyItemPojo> getMobileDetailMoneyInfo(Integer distributorMark, String corpid, String userId, Integer businessType, Integer subBusinessType, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        List<MobileDetailMoneyItemPojo> moneyItemList = new ArrayList<>();
        FieldAttrEntity refundUnAmountFieldAttrEntity = explainMap.get(RefundEnum.RETURN_AMOUNT.getAttr());
        if (refundUnAmountFieldAttrEntity != null && Objects.equals(refundUnAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
            Object refundUnAmount = AttrDecimalPrecisionHelper.moneyParseThrousandth(refundUnAmountFieldAttrEntity, paasFormDataEntityExt.getData(), RefundEnum.RETURN_AMOUNT.getAttr());
            moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.RETURN_AMOUNT) + UnitEnum.MONEY.getName(), refundUnAmount, false));
        }
        FieldAttrEntity refundRealAmountFieldAttrEntity = explainMap.get(RefundEnum.REFUND_AMOUNT.getAttr());
        if (refundRealAmountFieldAttrEntity != null && Objects.equals(refundRealAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
            Object refundRealAmount = AttrDecimalPrecisionHelper.moneyParseThrousandth(refundRealAmountFieldAttrEntity, paasFormDataEntityExt.getData(), RefundEnum.REFUND_AMOUNT.getAttr());
            moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.REFUND_AMOUNT) + UnitEnum.MONEY.getName(), refundRealAmount, false));
        }
        return moneyItemList;
    }

    @Override
    public JSONArray getBottomBlockInfo(String corpid, String userId, Integer businessType, PaasFormEntityExt formEntity, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt entityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("refundId", dataId);
        List<RefundUserEntity> refundUserEntityList = refundUserModel.findEntitys(param);
        Set<String> userIdIn = new HashSet<>();
        refundUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
        Map<String, UserEntity> userMap = new HashMap<>(userEntityList.size());
        userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
        List<CustomerUserPojo> userPojoList = new ArrayList<>();
        refundUserEntityList.forEach(item -> {
            UserEntity userEntity = userMap.get(item.getUserId());
            if (userEntity != null) {
                CustomerUserPojo refundUserPojo = new CustomerUserPojo(userEntity.getUserId(), userEntity.getName(), userEntity.getAvatar(), userEntity.getIsMain());
                userPojoList.add(refundUserPojo);
            }
        });
        JSONArray bottomBlockInfo = new JSONArray();
        bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

        Long refundId = FastJsonHelper.getLongOrDefaultFromFormData(entityExt.getData(), RefundEnum.CUSTOMER_ID.getAttr(), 0L);
        String refundCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(entityExt.getData(), RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), "");
        bottomBlockInfo.add(new MobileDetailDirectBlockPojo(refundId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), refundCustomerName));
        return bottomBlockInfo;
    }

    @Override
    public List<MobileDetailScriptPojo> getDetailShowScript(Integer businessType, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return setDetailShowScript(paasFormDataEntityExt, businessType, paasFormDataEntityExt.getData(), explainMap, RefundEnum.RETURN_AMOUNT.getAttr());
    }

    @Override
    public MobileDetailStatusPojo getDetailShowStatus(Integer businessType, JSONObject data) throws XbbException {
        return new MobileDetailStatusPojo();
    }

    @Override
    public Map<String, Object> getDetailShowOperation(String corpid, String userId, Integer businessType, Long dataId, JSONObject data) throws XbbException {
        return new HashMap<>(BasicConstant.ZERO);
    }

    @Override
    public JSONObject returnSaasObject(String corpid, Integer businessType, UserVO userVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        JSONObject saasReturnObj = new JSONObject();
        Boolean isOpen = contractPerformanceModel.openDistribution(corpid);
        saasReturnObj.put(CompanyConfigEnum.CONTRACT_PERFORMANCE_RULE_SET.getAlias(), isOpen);

        return saasReturnObj;
    }

    @Override
    public List<TopPermissionsPoJo> dingtalkHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONObject dataList = formData.getData();
        String corpid = formEntity.getCorpid();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer businessType = formEntity.getBusinessType();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());

        List<String> aliasIn = new ArrayList<>();
        workFlowEnumList.forEach(item -> aliasIn.add(XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias()));
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        List<TopPermissionsPoJo> topPermissions = businessButtonService.dingtalkDetailCommon(userVO, formEntity, explainMap, formData);
        if (Objects.isNull(dataList)) {
            return topPermissions;
        }
        String refundStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, RefundEnum.REFUND_STATUS.getAttr(), RefundStatusEnum.UNREFUND.getCode());
        Integer allInStock = getIntegerOrDefaultFromFormData(dataList, RefundEnum.ALL_IN_BOUND.getAttr(), BasicConstant.ONE);
        // 只有0:部分(未)入库时才展示按钮
        boolean isInStock = Objects.equals(allInStock, BasicConstant.ONE) || Objects.equals(allInStock, BasicConstant.TWO);
        boolean isOpened = Objects.equals(refundStatus, RefundStatusEnum.CLOSED.getCode());
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (isInStock && Objects.equals(workFlowEnum, WorkFlowEnum.REFUND_INSTOCK)) {
                continue;
            }
            if (isOpened && Objects.equals(workFlowEnum, WorkFlowEnum.REFUND_INSTOCK)) {
                continue;
            }
            TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
            BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
            if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                NameUtil.changeValue(paasBusinessTypeToName, topPermissionsPoJo);
            }
            topPermissions.add(topPermissionsPoJo);
        }
        List<LinkListPojo> linkList = formEntity.getLinkListList();
        topPermissions.addAll(linkListService.getDingtalkCommonButton(linkList, formData.getDel(), userVO, formData.getAppId(), formData.getFormId(), businessType, formEntity.getSaasMark(), corpid));
        return topPermissions;
    }

    @Override
    public List<WorkFlowPojo> webHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData) throws XbbException {
        UserVO userVO = handelDetailPojo.getLoginUser();
        Set<String> permSet = userVO.getPermSet();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermission(handelDetailPojo.getBusinessType(), permSet);
        // 获取对应businessType的alias
        List<String> aliasIn = WorkFlowEnum.getAliasIn(workFlowEnumList);
        String corpid = formData.getCorpid();
        Integer businessType = handelDetailPojo.getBusinessType();

        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
        JSONObject dataList = formData.getData();
        String refundStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, RefundEnum.REFUND_STATUS.getAttr(), RefundStatusEnum.UNREFUND.getCode());
        Integer allInStock = getIntegerOrDefaultFromFormData(dataList, RefundEnum.ALL_IN_BOUND.getAttr(), BasicConstant.ONE);
        // 只有0:部分(未)入库时才展示按钮
        boolean isInStock = Objects.equals(allInStock, BasicConstant.ONE) || Objects.equals(allInStock, BasicConstant.TWO);
        boolean isClosed = Objects.equals(refundStatus, RefundStatusEnum.CLOSED.getCode());
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (isInStock && Objects.equals(workFlowEnum, WorkFlowEnum.REFUND_INSTOCK)) {
                continue;
            }
            if (isClosed && Objects.equals(workFlowEnum,WorkFlowEnum.REFUND_INSTOCK)) {
                continue;
            }
            WorkFlowPojo workFlowPojo = new WorkFlowPojo();
            BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
            NameUtil.changeValue(paasBusinessTypeToName, workFlowPojo);
            workFlowPojoList.add(workFlowPojo);
        }
        return workFlowPojoList;
    }

    @Override
    public DataDetailPojo handleDetailData(Integer businessType, PaasFormDataEntityExt formData, String userId, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        DataDetailPojo dataDetailPojo = new DataDetailPojo();
        // 外链
        Integer outerLinkShare = setOuterLinkShare(handlerExplainDTO.getCorpid(), formData.getFormId());
        dataDetailPojo.setHasOuterLinkShare(outerLinkShare);
        return dataDetailPojo;
    }



    @Override
    public JSONArray getSecondTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<SummaryDataPoJo> summaryList = getSummaryList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return getSecondTitleList(summaryList, data, formDataDetailDTO.getCorpid(), formEntity.getId());
    }

    @Override
    public JSONArray getTagList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formEntity.getBusinessType();
        Long dataId = formData.getId();
        String userId = formDataDetailDTO.getUserId();
        List<SummaryDataPoJo> labelsList = getLabelList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return getTags(labelsList, corpid, businessType, dataId, userId);
    }

    @Override
    public String getTitle(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<FormTitlePoJo> formTitleList = getTitleList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return TitleUtil.getWebTitle(formTitleList);
    }

    @Override
    public List<DetailTabPojo> handleDetailTab(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap, HandlerExplainVO handlerExplainVO, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        UserVO userVO = handelDetailPojo.getLoginUser();
        String corpid = userVO.getCorpid();
        Integer businessType = handelDetailPojo.getBusinessType();

        List<BusinessDetailTabEnum>  tabEnumList = BusinessDetailTabEnum.getTabByBusinessTypeAndPermission(businessType, userVO.getPermSet(), handlerExplainDTO.getPlatform());
        // 获取对应businessType的alias
        List<String> aliasIn = BusinessDetailTabEnum.getAliasIn(tabEnumList);
        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        boolean openDistribution = contractPerformanceModel.openDistribution(corpid);
        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            if (!openDistribution && Objects.equals(tabEnum, BusinessDetailTabEnum.REFUND_PERFORMANCE)) {
                continue;
            }
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            NameUtil.changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
            detailTabPojo.setAttr(detailTabPojo.getKey());
            tabPojoList.add(detailTabPojo);
        }
        handleTeamTab(tabPojoList, explainMap);
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        handlerExplainVO.setAppId(formEntity.getAppId());
        handlerExplainVO.setFormId(formEntity.getId());
        // 公共tab
        tabPojoList.addAll(linkListService.commonTab(corpid, userVO, handlerExplainVO, handlerExplainDTO, businessType, formData.getDel(), linkList));
        // tab排序
        tabPojoList = detailTabConfigService.handleDetailTabSort(userVO.getUserId(), corpid, handlerExplainVO.getFormId(), businessType, tabPojoList);
        return tabPojoList;
    }


}
